<html>
<head>
  <title>Blog</title>
  <style>
    body {
      padding: 80px;
      font: 16px Helvetica, Arial;
    }
    h1 {
      font-size: 2em;
    }
    h2 {
      font-size: 1.2em;
    }
    #posts {
      margin: 0;
      padding: 0;
    }
    #posts li {
      margin: 40px 0;
      padding: 0;
      padding-bottom: 20px;
      border-bottom: 1px solid #eee;
      list-style: none;
    }
    #posts li:last-child {
      border-bottom: none;
    }
    textarea {
      width: 500px;
      height: 300px;
    }
    input[type=text],
    textarea {
      border: 1px solid #eee;
      border-top-color: #ddd;
      border-left-color: #ddd;
      border-radius: 2px;
      padding: 15px;
      font-size: .8em;
    }
    input[type=text] {
      width: 500px;
    }
  </style>
</head>
<body>
  <section id="content">
    <div id="login" class="panel">
      <button id="googleLoginBtn">Google Login</button>
      <!-- <button onclick="list()">List Posts</button> -->
    </div>
    <div id="list" class="panel">
      <h1>Posts</h1>
      <p>You have <strong id="postsLength"></strong> posts!</p>
      <p><a href="#/create/">Create a Post</a></p>
      <ul id="posts">
        <!--
        {% for post in posts %}
          <li>
            <h2>{{ post.title }}</h2>
            <p><a href="/post/{{ post.id }}">Read post</a></p>
          </li>
        {% endfor %}
        -->
      </ul>
    </div>
    <div id="create" class="panel">
      <h1>New Post</h1>
      <p>Create a new post.</p>
      <!-- <form action="/post" method="post"> -->
        <p><input type="text" placeholder="Title" id="postTitle"></p>
        <p><textarea placeholder="Contents" id="postBody"></textarea></p>
        <p><input type="button" value="Create" onclick="save()"></p>
      <!-- </form> -->
    </div>
    <div id="show" class="panel">
      <h1 id="showTitle"></h1>
      <p id="showBody"></p>
    </div>
  </section>
<script src="https://www.gstatic.com/firebasejs/4.8.2/firebase.js"></script>  
<script>
// Initialize Firebase
var config = {
  apiKey: "AIzaSyCmc44S50DGj-f9LbagNPLgnVHHaphIZhI",
  authDomain: "ccc-urspace.firebaseapp.com",
  databaseURL: "https://ccc-urspace.firebaseio.com",
  projectId: "ccc-urspace",
  storageBucket: "",
  messagingSenderId: "1023578722292"
};
firebase.initializeApp(config);

var googleProvider = new firebase.auth.GoogleAuthProvider();
//所需授權的Scope 
//查閱 https://developers.facebook.com/docs/facebook-login/permissions
// googleProvider.addScope('user_birthday');
googleProvider.setCustomParameters({
  'display': 'popup'
});

//使用Popup註冊FB方式
var googleLoginBtn = document.getElementById("googleLoginBtn");

googleLoginBtn.addEventListener("click", function () {
  firebase.auth().signInWithPopup(googleProvider).then(function(result) {
    // 取得 Google Token，可以使用於FB API中
    var token = result.credential.accessToken;
    // 使用者資料
    loginUser = result.user;
    console.log(loginUser);
  }).catch(function(error) {
    console.log('error=', error)
  })
})

var loginUser;
firebase.auth().onAuthStateChanged(function(pUser) {
  if (pUser) {
    loginUser = pUser;
    window.location.hash = '#/list/'
    console.log("User is logined", loginUser)
  } else {
  	loginUser = null;
    console.log("User is not logined yet.");
  }
})

function showPanel(id) {
  document.querySelectorAll('.panel').forEach((node) => node.style.display='none')
  document.getElementById(id).style.display = 'block'
}

let posts = []

function list() {
  var postsRef = firebase.database().ref('/user/' + loginUser.uid + '/posts/')
  var postsHtml = []
  posts = []
  postsRef.once('value').then(function(snapshot){
    let i=0
  	snapshot.forEach(function(childSnapshot) {
      let post = childSnapshot.val()
      post.id = childSnapshot.key
      posts.push(post)
      postsHtml.push(`<li><h2>${post.title}</h2><p><a href="#/show/${i++}">Read post</a></p></li>`)
      console.log(childSnapshot.val());
    })
    document.getElementById('posts').innerHTML = postsHtml.join('\n')
    document.getElementById('postsLength').innerHTML = posts.length
    showPanel('list')
  })
}

function save() {
  var title = document.getElementById('postTitle').value
  var body  = document.getElementById('postBody').value
  var postRef = firebase.database().ref('/user/' + loginUser.uid + '/posts/');
	postRef.push().set({
    title: title,
    body: body,
    time: firebase.database.ServerValue.TIMESTAMP
  }).then(function(){
    alert('Save Success!')
  }).catch(function(err){
  	console.error("Save Fail：", err);
    alert('Save Fail!')
  })
  list()
}

function show(match) {
  let i = parseInt(match[1])
  document.getElementById('showTitle').innerHTML = posts[i].title
  document.getElementById('showBody').innerHTML = posts[i].body
  showPanel('show')
}

function create(match) {
  showPanel('create')
}

let routeMap = [
  [/^\/?show\/(\w+)\/?$/, show],
  [/^\/?list\/?$/, list],
  [/^\/?create\/?$/, create],
]

window.onhashchange = function () {
  console.log('onhashchange')
  var hash = window.location.hash.trim().substring(1)
  console.log('onhashchange:hash=%s', hash)
  for (let [regexp, f] of routeMap) {
    var m = hash.match(regexp)
    if (m) {
      console.log('match:m=%j', m)
      f(m, hash)
      break
    }
  }
}
/*
window.onload = function() {
  window.location.hash = '#/list/'
}
*/

</script>
</body>
</html>